<template>
  <div class="index-box" ref="index">
    <el-row :gutter="10">
      <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
        <div class="search" ref="search">
          <el-form :inline="true" :model="searchForm" size="small" ref="searchForm" @submit.native.prevent class="demo-form-inline" id="searchBox">
            <el-form-item prop="telephone">
                <el-input v-model="searchForm.telephone" clearable placeholder="用户手机号"></el-input>
            </el-form-item>
            <el-form-item prop="consumptionTime">
              <el-date-picker v-model="consumptionTime" type="daterange" align="right" unlink-panels range-separator="至"
                start-placeholder="获取消费券开始日期" end-placeholder="获取消费券结束日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                :picker-options="pickerOptions">
              </el-date-picker>
            </el-form-item>
            <el-form-item prop="firstorderTime">
              <el-date-picker v-model="firstorderTime" type="daterange" align="right" unlink-panels range-separator="至"
                start-placeholder="首次下单开始日期" end-placeholder="首次下单结束日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                :picker-options="pickerOptions">
              </el-date-picker>
            </el-form-item>

            <el-form-item class="clearfix">
              <el-button type="primary" @click="handleSearch()" icon="el-icon-search">搜索</el-button>
              <el-button icon="el-icon-refresh" size="small" @click="resetSearch">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
        <div class="actionBtn" ref="actionBtn">
          <div class="actionBtnLeft">
            <el-radio-group v-model="searchForm.levelId" size="small" @change="handleSearch">
              <el-radio-button label="">全部</el-radio-button>
              <el-radio-button :label="item.levelId" v-for="item in levelList">{{item.name}}</el-radio-button>
            </el-radio-group>
            <el-button
              style="margin-left:10px"
              type="warning"
              icon="el-icon-download"
              size="small"
              :loading="btnLoading"
              v-has="'statistics:deal:down'"
              @click="handleExport"
            >导出</el-button>

          </div>
          <div class="actionBtnRight">
              <MyRefresh></MyRefresh>
              <MyTableColumnSet :tableColumn.sync="tableColumn" :hideTableColumn.sync="hideTableColumn" :tableColumnType.sync="tableColumnType"></MyTableColumnSet>
          </div>
        </div>

        <div class="table" ref="table">
          <el-table :data="dataList" style="width: 100%;"  border :height="tableHeight" stripe v-loading="loading">

            <el-table-column prop="userface" label="用户头像" v-if="!hideTableColumn.includes('userface')" width="80" align="center">
              <template #default="scope">
                 <el-image :src="scope.row.userface" fit="fill" v-image-preview="scope.row.userface" class="img"></el-image>
              </template>
            </el-table-column>
            <el-table-column prop="telephone" label="用户手机号" v-if="!hideTableColumn.includes('telephone')" align="center" width="130"></el-table-column>
            <el-table-column prop="nickname" label="用户名" v-if="!hideTableColumn.includes('nickname')" align="center" width="200" show-overflow-tooltip></el-table-column>
            <el-table-column prop="memberLevelName" label="会员等级" v-if="!hideTableColumn.includes('memberLevelName')" align="center" width="120"></el-table-column>
            <el-table-column prop="totalCoupon" label="获取消费券金额(元)" v-if="!hideTableColumn.includes('totalCoupon')" align="center" width="150"></el-table-column>
            <el-table-column prop="usableCoupon" label="消费券可用额(元)" v-if="!hideTableColumn.includes('usableCoupon')" align="center" width="150"></el-table-column>
            <el-table-column prop="firstCreateOrderTime" label="首次下单时间" v-if="!hideTableColumn.includes('firstCreateOrderTime')" align="center" width="160"></el-table-column>
            <el-table-column prop="orderCount" label="下单数量(单)" v-if="!hideTableColumn.includes('orderCount')" align="center" width="160"></el-table-column>
            <el-table-column prop="orderTotal" label="订单总金额(元)" v-if="!hideTableColumn.includes('orderTotal')" align="center" width="150"></el-table-column>
            <el-table-column prop="orderCompleteCount" label="订单完成数量(单)" v-if="!hideTableColumn.includes('orderCompleteCount')" align="center" width="150"></el-table-column>
            <el-table-column prop="orderCompleteTotal" label="交易完成金额(元)" v-if="!hideTableColumn.includes('orderCompleteTotal')" align="center" width="150"></el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  icon="el-icon-s-ticket"
                  @click="handleTicket(scope.row)"
                  v-has="'system:dictionaries:edit'"
                >消费券明细</el-button>
                <el-button
                  type="text"
                  icon="el-icon-s-order"
                  @click="handleOrderDetail(scope.row)"
                  v-has="'system:dictionaries:del'"
                >订单明细</el-button>
              </template>
            </el-table-column>


          </el-table>
        </div>
        <div class="page" ref="page">
           <MyPagination
              v-show="total"
             :total="total"
             :page.sync="searchForm.pageNum"
             :limit.sync="searchForm.pageSize"
             @pagination="dataInfo"
           />
        </div>
      </el-col>
    </el-row>

    <el-dialog title="消费券明细" width="800px" :close-on-click-modal="false" v-dialogDrag :visible.sync="ticketVisible" @close="ticketVisible = false">
      <div style="margin-bottom: 10px;">手机号为 <span class="red"> {{statusRow.telephone}} ({{statusRow.memberLevelName}}) </span>的消费券明细</div>
      <div>消费券可用金额：{{statusRow.usableCoupon}}</div>
      <div style="margin-bottom: 10px;">消费券已用金额：{{statusRow.totalCoupon-statusRow.usableCoupon}}</div>
      <div class="search" ref="search">
        <el-form :inline="true" :model="searchForm" size="small" ref="searchForm" @submit.native.prevent class="demo-form-inline" id="searchBox">
          <el-form-item prop="sourceTime">
            <el-date-picker v-model="sourceTime" type="daterange" align="right" unlink-panels range-separator="至"
              start-placeholder="来源日期开始日期" end-placeholder="来源日期结束日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
              :picker-options="pickerOptions">
            </el-date-picker>
          </el-form-item>
          <el-form-item class="clearfix">
            <el-button type="primary" @click="handleTicketSearch()" icon="el-icon-search">搜索</el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-table :data="ticketList" style="width: 100%;"  border  stripe v-loading="ticketLoading">
        <el-table-column prop="sourceDate" label="来源日期"  align="center" ></el-table-column>
        <el-table-column prop="couponTypeName" label="券类型"  align="center" ></el-table-column>
        <el-table-column prop="couponAmount" label="消费券金额(元)"  align="center" ></el-table-column>
        <el-table-column prop="orderCompleteCount" label="领取状态" align="center" >
          <template slot-scope="scope">
            <el-tag v-if="scope.row.status=='1'">待领取</el-tag>
            <el-tag v-else-if="scope.row.status=='2'" type="success">已领取</el-tag>
            <el-tag v-else-if="scope.row.status=='3'" type="warning">已过期</el-tag>
          </template>
        </el-table-column>
      </el-table>
      <MyPagination
        :total="ticketTotal"
        :page.sync="ticketForm.pageNum"
        :limit.sync="ticketForm.pageSize"
        @pagination="ticketDataInfo"
      />
    </el-dialog>

  </div>
</template>

<script>
  import common from '@/api/api';
  import option from '../../../common/option.js';
  import {
   transactionStatisticsList,getAllMemberLevel,transactionStatisticsExport,couponItemList
  } from '@/api/getData'
  export default {
    data() {
      return {
        loading: false,
        btnLoading: false,
        consumptionTime:[],
        firstorderTime:[],
        searchForm: {
          telephone:'',
          levelId:'',
          pageNum: 1,
          pageSize: 20,
        },
        total: 0,
        tableColumn:[{/*自定义表格列*/
            name:'用户头像',
            value:'userface'
        },{
            name:'用户手机号',
            value:'telephone'
        },{
            name:'用户名',
            value:'nickname'
        },{
            name:'会员等级',
            value:'memberLevelName'
        },{
            name:'获取消费券金额(元)',
            value:'totalCoupon'
        },{
            name:'消费券可用额(元)',
            value:'usableCoupon'
        },{
            name:'首次下单时间',
            value:'firstCreateOrderTime'
        },{
            name:'下单数量(单)',
            value:'orderCount'
        },{
            name:'订单总金额(元',
            value:'orderTotal'
        },{
            name:'订单完成数量(单)',
            value:'orderCompleteCount'
        },{
            name:'交易完成金额(元',
            value:'orderCompleteTotal'
        }],
        hideTableColumn:[],/*自定义表格列需要隐藏的*/
        tableColumnType:'staffManagement',/*自定义表格列类型传参*/
        tableHeight:0,//table 高度
        dataList:[],

        multipleSelection: '',
        dialogTitle: '',
        statusRow:{},/*活跃的列*/
        levelList:[],
        ticketVisible:false,
        sourceTime:[],
        ticketForm:{
          customerId:'',
          pageNum:1,
          pageSize:20,
        },
        ticketList:[],
        ticketTotal:0,
        ticketLoading:false
      }
    },
    computed: {
      pickerOptions: () => {
        return option.pickerOptions;
      }
    },
    mounted() {
      this.dataInfo();
      this.getSelect();
      this.$nextTick(() => {
          this.tableHeight = this.$refs.index.offsetHeight - this.$refs.search.offsetHeight - this.$refs.actionBtn.offsetHeight - this.$refs.page.offsetHeight - 55;
      })
    },
    methods: {
      handleOrderDetail(row){
         this.$router.push({path:'/statistics/userOrderDetail',query:{customerId:row.customerId,phone:row.telephone,levelName:row.memberLevelName}});
      },
      handleTicket(row){
        this.statusRow = row;
        this.ticketForm.customerId = row.customerId;
        this.ticketVisible = true;
        this.ticketDataInfo();
      },
      handleTicketSearch(){
        this.ticketForm.pageNum = 1;
        this.ticketDataInfo();
      },
      async ticketDataInfo(){
        try {
          let data = this.addDateRange(this.ticketForm, this.sourceTime, 'sourceStartTime', 'sourceEndTime');
          this.ticketLoading = true
           const result = await couponItemList(data);
           if (result.code == 200) {
             this.ticketTotal = result.total;
             this.ticketList = result.rows;
           } else {
             this.$message.error(result.msg);
           }
           this.ticketLoading = false;
        } catch (err) {
          this.ticketLoading = false;
          console.log(err)
        }
      },

      /** 导出按钮操作 */
       handleExport() {
        let data = this.addDateRange(this.searchForm, this.consumptionTime, 'obtainCouponStartTime', 'obtainCouponEndTime');
        data = this.addDateRange(this.searchForm, this.firstorderTime, 'firstCreateOrderStartTime', 'firstCreateOrderEndTime');
         this.$modal.confirm('是否确认导出搜索数据项？').then(() => {
           this.btnLoading = true;
           return transactionStatisticsExport(data);
         }).then(response => {
           this.$download.name(response.msg);
           this.btnLoading = false;
         }).catch(() => {});
      },
      /** 数据初始化请求动态列表数据 **/
      getSelect(){
        getAllMemberLevel().then(res=>{
          let list = res.data;
          list.map(item=>{
            item.nameMoney = item.levelId!='1'?item.name+"("+item.unionFee+"万元加盟金)":item.name
          })
          this.levelList = list;
        })
      },
      async dataInfo() {
        try {
          let data = this.addDateRange(this.searchForm, this.consumptionTime, 'obtainCouponStartTime', 'obtainCouponEndTime');
          data = this.addDateRange(this.searchForm, this.firstorderTime, 'firstCreateOrderStartTime', 'firstCreateOrderEndTime');
          this.loading = true;
          const result = await transactionStatisticsList(data);
          if (result.code == 200) {
            this.total = result.total;
            this.dataList = result.rows;
          } else {
            this.$message.error(result.msg);
          }
          this.loading = false;
        } catch (err) {
          this.loading = false;
          console.log(err)
        }
      },

      handleSearch() {
        this.searchForm.pageNum= 1;
        this.dataInfo();
      },
      resetSearch(){
        this.resetForm('searchForm');
        this.consumptionTime = [];
        this.firstorderTime = [];
        this.searchForm.pageNum = 1;
        this.dataInfo();
      },
      /** 表格选中状态改变 **/
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },

    }
  }
</script>

<style scoped lang="scss">

  .title{
    text-align: center;
    margin:5px 0;
  }
  .el-table .el-dropdown-link{
      cursor: pointer;
      color: #61997A;
      margin-left: 5px;
  }
    .leftDialog{
      height:540px;
      overflow-y: auto;
    }
    .activeVerticalBox .activeItem{
      color:#61997A;
      cursor: pointer;
      margin: 0px;
      text-align: center;
      height:20px;
      line-height: 20px;
    }
    .activeVerticalBox .el-dropdown{
      display: flex;
      justify-content: center;
      color:#61997A;
      cursor: pointer;
    }
    .activeCheckedBox{
      border-top: 1px solid #ddd;
      padding:10px;
      height:52px;
      .el-tag{
        margin-right:10px;
      }
    }

</style>
